# -*- coding: utf-8 -*-
import traceback
import requests
import json
import logging

from app.db.crud import get_not_ttl_posts_with_source_sql
from app.db.database import SessionLocal
from sqlalchemy import update
from app.db.models import TPost
from app.myttl.tts_automation import TTSAutomation, Article
from app.monitor import status_manager

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('tts_automation.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


class TtlWorker:
    def __init__(self):
        self.name = 'TTLWorker'
 
    def run(self):
        # 获取最近24小时ttl字段为空并且有content字段的文章数据,然后进行循环调用tts类进行音频的生成,并打印结果
        with SessionLocal() as db:
            try:
                posts = get_not_ttl_posts_with_source_sql(db, None)
                if not posts:
                    logger.info("No posts found for TTS processing")
                    return

                tts = TTSAutomation()
                articles_for_tts = []
                
                # 准备文章列表
                for post in posts:
                    try:
                        article = Article(id=post.post_id, content=post.short_content)
                        articles_for_tts.append(article)
                    except Exception as e:
                        error_msg = f"准备TTS文章失败 (ID: {post.post_id}): {str(e)}"
                        status_manager.record_error('tts_generation', error_msg)
                        logger.error(error_msg)
                        continue

                # 批量处理TTS生成
                try:
                    results = tts.process_articles(articles_for_tts)
                    for article_id, filepath in results.items():
                        if filepath:  # 如果生成成功
                            status_manager.increment_count('tts_generation')
                            logger.info(f"Article {article_id} -> {filepath}")
                        else:  # 如果生成失败
                            error_msg = f"TTS生成失败 (ID: {article_id})"
                            status_manager.record_error('tts_generation', error_msg)
                            logger.error(error_msg)
                except Exception as e:
                    error_msg = f"TTS批量处理失败: {str(e)}"
                    status_manager.record_error('tts_generation', error_msg)
                    logger.error(error_msg)
                    logger.error(traceback.format_exc())

            except Exception as e:
                error_msg = f"TTS Worker运行失败: {str(e)}"
                status_manager.record_error('tts_generation', error_msg)
                logger.error(error_msg)
                logger.error(traceback.format_exc())

if __name__ == '__main__':
    worker = TtlWorker()
    worker.run()
